<template>
  <el-form
    ref="form"
    class="form"
    :model="form"
    :rules="rules"
  >
    <el-form-item class="form-item" prop="username">
      <el-input
        v-model="form.username"
        placeholder="用户名/手机"
        @focus="clearErrorTips('username')"
      />
    </el-form-item>

    <el-form-item class="form-item" prop="password">
      <el-input
        v-model="form.password"
        placeholder="密码"
        type="password"
        @focus="clearErrorTips('password')"
      />
    </el-form-item>

    <p class="form-text">
      <nuxt-link to="#">
        忘记密码
      </nuxt-link>
    </p>

    <el-button
      class="submit"
      type="primary"
      @click="login"
    >
      登录
    </el-button>
  </el-form>
</template>

<script>
export default {
  name: 'LoginForm',
  data () {
    return {
      form: {
        username: '13800138000',
        password: '12345'
      },
      rules: {
        username: [{
          required: true,
          message: '请输入正确的用户名或手机号',
          trigger: 'blur',
          pattern: /^1[345678]\d{9}$/
        }],
        password: [{
          required: true,
          message: '请输入正确的密码',
          trigger: 'blur',
          min: 5,
          max: 12
        }]
      }
    }
  },
  methods: {
    login () {
      // 先验证表单
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$axios.post('/accounts/login', this.form).then((res) => {
            if (res.data.token) {
              this.$store.commit('setUserInfo', res.data)
              this.$message.success('登录成功')
              if (this.$route.params.from === 'order') {
                // 这里是判断登录页是否是从订单页跳转过来的，如果是就调回去，这里我曾尝试过用$router.back()，但是会有bug，因为订单页面是依赖url上的参数来获取数据的，如果我用$router.back()跳转到订单页有时会丢失掉url上的参数，所以我干脆从order页面跳过lai时把query参数传过来，这里再用push的方式传回去。
                this.$router.push({
                  path: '/air/order',
                  query: this.$route.params.query
                })
              } else {
                this.$router.push('/')
              }
            }
          })
        }
      })
    },
    clearErrorTips (prop) {
      this.$refs.form.clearValidate(prop)
    }
  }
}
</script>

<style scoped lang="less">
.form{
        padding:25px;
    }

    .form-item{
        margin-bottom:20px;
    }

    .form-text{
        font-size:12px;
        color:#409EFF;
        text-align: right;
        line-height: 1;
    }

    .submit{
        width:100%;
        margin-top:10px;
    }
</style>
